package cn.edu.thu.laud.auth;
/*
 * 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * 
 */


import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.cassandra.auth.AuthenticatedUser;
import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.thrift.AuthenticationException;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.KeySlice;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.thu.laud.thrift.LaUDAdministrator;

public class SimpleAuthenticator extends MemoryAuthenticator implements IAuthenticator 
{
    public final static String PASSWD_FILENAME_PROPERTY        = "passwd.properties";
//    public final static String PMODE_PROPERTY                  = "passwd.mode";
    public static final String USERNAME_KEY                    = "username";
    public static final String PASSWORD_KEY                    = "password";

    Logger logger= LoggerFactory.getLogger(SimpleAuthenticator.class);
    
    
    
//    public enum PasswordMode
//    {
//        PLAIN, MD5,
//    };

    public AuthenticatedUser defaultUser()
    {
        // users must log in
    	logger.debug("defaultUser");
        return null;
    }

    public AuthenticatedUser authenticate(Map<? extends CharSequence,? extends CharSequence> credentials) throws AuthenticationException
    {
    	logger.debug("authenticate--begin");
//    	for(CharSequence c:credentials.keySet()){
//    		logger.debug("key:"+c+";value:"+credentials.get(c));
//    	}
//    	logger.debug("authenticate--end");
        String username = null;
        CharSequence user = credentials.get(USERNAME_KEY);
        if (null == user) 
            throw new AuthenticationException("Authentication request was missing the required key '" + USERNAME_KEY + "'");
        else
            username = user.toString();

        //daemonClient can not login from Client.
        if(username.equals("root")){
        	throw new AuthenticationException("root user could not login in this way.");
        }
        
        
        String password = null;
        CharSequence pass = credentials.get(PASSWORD_KEY);
        if (null == pass) 
            throw new AuthenticationException("Authentication request was missing the required key '" + PASSWORD_KEY + "'");
        else
            password = pass.toString();

        boolean authenticated = false;

        List<ColumnOrSuperColumn> infos=userBasicInfos.get(username);
        String rightPwd="";
        if(infos!=null){
        	for(ColumnOrSuperColumn column:infos){
        		if(column.column.name.equals(LaUDAdministrator.PWD_COLUMN_BYTE)){
        			rightPwd=UTF8Type.instance.compose(column.column.value);
        		}
        	}
        	authenticated= password.equals(rightPwd);
        }else{
        	throw new AuthenticationException("missing info about user:"+username);
        }
 

        if (!authenticated) throw new AuthenticationException("Given password   could not be validated for user "+username);

        return new AuthenticatedUser(username);
    }

    public void validateConfiguration() throws ConfigurationException
    {
    	logger.debug("validateConfiguration");
//        String pfilename = System.getProperty(SimpleAuthenticator.PASSWD_FILENAME_PROPERTY);
//        if (pfilename == null)
//        {
//            throw new ConfigurationException("When using " + this.getClass().getCanonicalName() + " " + 
//                    SimpleAuthenticator.PASSWD_FILENAME_PROPERTY + " properties must be defined.");	
//        }
    }

 
}
